package deepbitview

import grails.converters.JSON
import grails.converters.JSON
import javax.net.ssl.SSLContext
import javax.net.ssl.HttpsURLConnection

/**
 * provides access to the mtgox ticker and so fetches recent results
 * for you
 */
class TickerService {

    static ERROR_CODE = -1
    static transactional = true

    /**
     * returns the latest usd exchange rate for a bitcoin
     * @return
     */
    double fetchLatestUSDExchangeRate() {

        try {

            TrustManager.generateTrustedSSL()

            //parse our data to a json object
            Map jsonArray = JSON.parse(new InputStreamReader(new URL("https://mtgox.com/code/data/ticker.php").openStream()))

            log.info("fetching ticker: ${jsonArray}")

            double rate = jsonArray.get("ticker").get("last")

            return rate

        }
        catch (Exception e) {
            e.printStackTrace()

            return ERROR_CODE
        }
    }


}
